import sqlalchemy
from sqlalchemy.orm import sessionmaker
import Model

class DBConnections(object):
    def __init__(self):
        self._connections = dict()
        
        #default connections
        self.createConnection('app', 'sqlite:///test.db')

    def createConnection(self, name, url, autoCommit=True, **kwargs):
        if (self._connections.has_key(name)):
            raise Exception("connection '%s' already exists" % (name))
        
        #create the engine
        engine = sqlalchemy.create_engine(url, **kwargs)
        
        #create the object to instanciate the connection
        sess = sessionmaker(bind=engine, autoflush=True, autocommit=autoCommit)
        sess = sess()
        sess._my_engine = engine
        
        #test the connection
        sess.connection()
        
        self._connections[name] = sess
        
        return sess

    def getConnection(self, name):
        if (not self._connections.has_key(name)):
            raise Exception("invalid connection '%s'" % (name))
            
        return self._connections[name]
